package filial;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;

import bank.IBankmanager;
import bank.IKonto;

public class FilialController {

  public static String Namensdienst = "localhost";
  public static int blz = 55555555;
  // public static int blz = 20050550;

  IBankmanager bank;

  public FilialController() {
    try {
      bank = (IBankmanager) Naming.lookup("//" + Namensdienst + "/" + blz);
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (RemoteException e) {
      e.printStackTrace();
    } catch (NotBoundException e) {
      e.printStackTrace();
    }
  }

  private IKonto lookupKonto(String id) throws Exception {

    IKonto konto = null;
    konto = (IKonto) Naming.lookup("//" + Namensdienst + "/" + id);
    return konto;
  }

  public String kontoEinrichten() throws RemoteException {
    return bank.kontoEinrichten();
  }

  public double einzahlen(String kontoID, double betrag) throws Exception {

    IKonto konto = lookupKonto(kontoID);
    return konto.einzahlen(betrag);

  }

  public double abheben(String kontoID, double betrag) throws Exception {
    IKonto konto = lookupKonto(kontoID);
    return konto.abheben(betrag);
  }

  public double kontoStand(String kontoID) throws Exception {
    IKonto konto = lookupKonto(kontoID);
    return konto.kontoStand();
  }

  public double ueberweisen(double betrag, String fromID, String toID) throws Exception {
    IKonto konto = lookupKonto(fromID);
    return konto.ueberweisen(betrag, toID);
  }

  public List<String> getAccounts() {

    String[] all = null;
    List<String> accounts = new ArrayList<String>();
    try {
      all = Naming.list("//" + Namensdienst + "/");
    } catch (RemoteException e) {
      e.printStackTrace();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }
    for (String name : all) {
      if (name.contains("_") == true) {
        int index = name.lastIndexOf("/");
        accounts.add(name.substring(index + 1));
      }
    }
    return accounts;
  }

}
